package com.bw.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bw.home.R
import com.bw.home.entity.VideoEntityItem
import com.bw.home.entity.VideoTypeEntityItem
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.material.imageview.ShapeableImageView

class VideoAdapter : RecyclerView.Adapter<VideoAdapter.VideoViewHolder>() {

    private var videoList: List<VideoEntityItem> = emptyList()
    private var onItemClickListener: ((VideoEntityItem) -> Unit)? = null
    private var selectedPosition = 0

    private var currentPlayer: SimpleExoPlayer? = null


    fun setData(list: List<VideoEntityItem>) {
        this.videoList = list
        notifyDataSetChanged()
    }

    fun setOnItemClickListener(listener: (VideoEntityItem) -> Unit) {
        this.onItemClickListener = listener
    }

    fun setSelectedPosition(position: Int) {
        val oldPosition = selectedPosition
        selectedPosition = position
        notifyItemChanged(oldPosition)
        notifyItemChanged(selectedPosition)
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): VideoViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.home, parent, false)
        return VideoViewHolder(view)
    }

    override fun onBindViewHolder(
        holder: VideoViewHolder,
        position: Int
    ) {
        val videoItem = videoList[position]

        // 绑定视频数据到 PlayerView
        holder.bind(videoItem)

        // 点击事件
        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(videoItem)
            setSelectedPosition(position)
        }
    }


    override fun getItemCount(): Int = videoList.size

    inner class VideoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val playerView: PlayerView = itemView.findViewById(R.id.playerView)
        private val userAvatar: ShapeableImageView = itemView.findViewById(R.id.userAvatar)
        private val userName: TextView = itemView.findViewById(R.id.userName)
        private val userDescription: TextView = itemView.findViewById(R.id.userDescription)
        private val rightImage1: ImageView = itemView.findViewById(R.id.rightImage1)
        private val rightImage2: ImageView = itemView.findViewById(R.id.rightImage2)

        private var exoPlayer: SimpleExoPlayer? = null

        fun bind(videoItem: VideoEntityItem) {
            // 初始化 ExoPlayer
            val context = itemView.context
            exoPlayer = SimpleExoPlayer.Builder(context).build()
            playerView.player = exoPlayer

            // 设置视频源（假设 VideoEntityItem 有 videoUrl 字段）
            val mediaItem = MediaItem.fromUri(videoItem.videopath)
            exoPlayer?.setMediaItem(mediaItem)
            exoPlayer?.prepare()

            // 如果是选中项，自动播放；否则暂停
            if (adapterPosition == selectedPosition) {
                exoPlayer?.play()
                currentPlayer = exoPlayer // 保存当前播放的 Player
            } else {
                exoPlayer?.pause()
            }

            Glide.with(itemView.context)
                .load(videoItem.avatar_url)
                .circleCrop()
                .into(userAvatar)
            userName.text = videoItem.name
            userDescription.text = videoItem. description

        }

        // 释放 Player 资源（防止内存泄漏）
        fun releasePlayer() {
            exoPlayer?.release()
            exoPlayer = null
        }


    }

    // 在 Activity/Fragment 销毁时释放 Player
    fun releaseAllPlayers() {
        currentPlayer?.release()
        currentPlayer = null
    }

}